/**
 * 
 */
package com.kadapatha.web.user;

import java.util.Set;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kadapatha.domain.user.User;
import com.kadapatha.service.api.user.UserService;
import com.kadapatha.service.exception.ServiceException;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;

	private final Validator validator;

	@Autowired
	public UserController(final Validator validator) {
		this.validator = validator;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(final Model model) {
		model.addAttribute(new UserForm());
		return "user/createUserForm";
	}

	@RequestMapping(value = "/isExist", method = RequestMethod.GET)
	public @ResponseBody
	boolean isExist(@RequestParam final String userName) {
		try {
			return userService.isExist(userName);
		} catch (final ServiceException e) {
			return true;
		}
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public @ResponseBody
	UserForm create(@RequestBody final UserForm userForm,
			final HttpServletResponse response) {
		final Set<ConstraintViolation<UserForm>> failures = validator
				.validate(userForm);
		if (!failures.isEmpty()) {
			userForm.addValidationMessages(failures);
		} else {
			try {

				final User user = userService.saveUser(new User(userForm
						.getId() <= 0 ? null : userForm.getId(), userForm
						.getUserName(), userForm.getFirstName(), userForm
						.getMiddleName().toLowerCase(), userForm.getLastName(),
						userForm.getEmail(), userForm.getLastName(), true));
				userForm.setId(user.getId());

			} catch (final ServiceException exception) {
				userForm.handleException(exception);
			}
		}
		return userForm;
	}

}
